(function () {
	
    //table数据显示
	//网格
	var serverDataGrid = {};
	serverDataGrid.divisionId = "0";
    var	serverTableGrid;
	
    //未绑定
    var serverDataPart = {};
    serverDataPart.gridId = 'isNull';
    var	serverTablePart;
    
    //已绑定
    var serverDataPartOnGrid = {};
    serverDataPartOnGrid.gridId = "0";
    var	serverTablePartOnGrid;
    jQuery(document).ready(function () {
    	
    		serverTableGrid = jQuery('#dataTableGrid').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "post",
                "cache": false,
                "url": window.rootPath+'/ui/bindingGridArea/getGridAreaPage',
                "data": function (d) {
                    return $.extend({}, d, serverDataGrid);
                }
            },
            columns: [
	        		{
		            data: null,
		            defaultContent: ""
	        		},
	            {
	        			data: 'gridName'
	            },
	            {
	            		data: 'division.divisionName'
	            },
	            {
	            		data: 'gridArea'
	            },
	            {
	            		data: 'typeOpt.title'
	            },
	            {
	            		data: 'gridState.title'
	            }],
            "drawCallback": function ( oSettings ) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
                {
                    $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
                    k++;
                }

                serverTableGrid.off('click','tr');
                serverTableGrid.on( 'click', 'tr', function (event) {
                    event=event||window.event;
                    var target=event.target||event.scrElement;
                    var data = serverTableGrid.row( this ).data();

	            	    if($(this).hasClass('selected') ){
	            			$(this).removeClass('selected');
	            			serverDataPartOnGrid.gridId = "0";
	            		}else{
	            	    		serverTableGrid.$('tr.selected').removeClass('selected');
	            	    		$(this).addClass('selected');
	            	    		//获取当前行数据
	            	    		var data = serverTableGrid.row(this).data();
	            	    		serverDataPartOnGrid.gridId = data.id;
	            	    }
	            	    serverTablePartOnGrid.draw(false);
                    return;
                } );
            }
        });
        
    		//未绑定表格
    		serverTablePart = jQuery('#dataTablePart').DataTable({
	        	"serverSide": true,
	        	"ordering": false,
	        	"ajax": {
	        		"dataType": "json",
	        		"type": "post",
	        		"cache": false,
	        		"url": window.rootPath+'/ui/bindingGridArea/getPartPageByGrid',
	        		"data": function (d) {
	        			return $.extend({}, d, serverDataPart);
	        		}
	        	},
	        	columns: [
	        		{
	        			data: null,
	        			defaultContent: ""
	        		},
	        		{
                    data: 'id',
                    render: function (data, type, full, meta) {
                        var operate ='<input type="checkbox" dataId="'+data+'" group="addDate"/>';
                        return operate;
                    }
	        		},
	        		{
	        			data: 'partName'
	        		},
	        		{
	        			data: 'hierarchy',
	        			render: function (data, type, full, meta) {
	        				if (data)
	        					return data.groupName;
	        				else
	        					return '';
	        			}
	        		},
	        		{
	        			data: 'part.partName'
	        		},
	        		{
	        			data: 'state.title'
	        		},
	        		{
	        			data:null,
	        			defaultContent: "",
	        			render: function(data, type, full, meta){
	        				var operate = '<button type="button" class="btn btn-sm btn-info addNode" title="绑定"><i class="fa fa-sign-in"></i></button>';
	        				return operate;
        			}
        		}],
        		"drawCallback": function ( oSettings ) {
        			var k = 0;
        			var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
        			
        			for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
        			{
        				$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
        				k++;
        			}
        			
        			serverTablePart.off('click','tr');
        			serverTablePart.on( 'click', 'tr', function (event) {
        				event=event||window.event;
        				var target=event.target||event.scrElement;
        				var data = serverTablePart.row(this).data();
        				
        				if(target.className.indexOf('fa-sign-in')!=-1||target.className.indexOf('addNode')!=-1){
        					addData(data,data.partName);
        				}
        				return;
        			} );
        		}
        });	
        	//已绑定表格
        	serverTablePartOnGrid = jQuery('#dataTablePartOnGrid').DataTable({
        		"serverSide": true,
        		"ordering": false,
        		"ajax": {
        			"dataType": "json",
        			"type": "post",
        			"cache": false,
        			"url": window.rootPath+'/ui/bindingGridArea/getPartPageByGrid',
        			"data": function (d) {
        				return $.extend({}, d, serverDataPartOnGrid);
        			}
        		},
        		columns: [
        			{
        				data: null,
        				defaultContent: ""
        			},
        			{
                    data: 'id',
                    render: function (data, type, full, meta) {
                        var operate ='<input type="checkbox" dataId="'+data+'" group="removeDate"/>';
                        return operate;
                    }
    	        		},
        			{
        				data: 'partName'
        			},
        			{
        				data: 'hierarchy',
        				render: function (data, type, full, meta) {
        					if (data)
        						return data.groupName;
        					else
        						return '';
        				}
        			},
        			{
        				data: 'part.partName'
        			},
        			{
        				data: 'state.title'
        			},
        			{
        				data:null,
        				defaultContent: "",
        				render: function(data, type, full, meta){
        					var operate = '<button type="button" class="btn btn-sm btn-info addNode" title="移除"><i class="fa fa-remove"></i></button>';
        					return operate;
        				}
        			}],
        			"drawCallback": function ( oSettings ) {
        				var k = 0;
        				var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
        				
        				for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
        				{
        					$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
        					k++;
        				}
        				
        				serverTablePartOnGrid.off('click','tr');
        				serverTablePartOnGrid.on( 'click', 'tr', function (event) {
        					event=event||window.event;
        					var target=event.target||event.scrElement;
        					var data = serverTablePartOnGrid.row(this).data();
        					
        					if(target.className.indexOf('fa-remove')!=-1||target.className.indexOf('addNode')!=-1){
        						removeData(data,data.partName);
        					}
        					return;
        				} );
        			}
        	});
        
        //未绑定查询
        jQuery('.searchBtnPart').on('click',function(){
        		serverDataPart.key=jQuery('#searchPart').val();
        		serverTablePart.draw();
        })
        
        //未绑定撤销查询
        jQuery('.resetBtnPart').on("click",function()
        {
            jQuery('#searchPart').val('');
            serverDataPart.key ='';
            serverTablePart.draw();
        });
        
        //已绑定查询
        jQuery('.searchBtnPartOnGrid').on('click',function(){
	        	if(serverDataPartOnGrid.gridId == '0'){
	    			message('请选择网格信息!');
	    			return;
	    		}
	        	serverDataPartOnGrid.key=jQuery('#searchPartOnGrid').val();
	        	serverTablePartOnGrid.draw();
        })
        
        //已绑定撤销查询
        jQuery('.resetBtnPartOnGrid').on("click",function(){
	        	jQuery('#searchPartOnGrid').val('');
	        	serverDataPartOnGrid.key ='';
	        	serverTablePartOnGrid.draw();
    		});
        
        
    });

    
    //未绑定 全选
    $("#allPart").click(function() {
    		var addDate = $(":checkbox[group=addDate]");
        if ($(this).prop("checked")) {
        		addDate.each(function() {
                $(this).prop("checked", true);  
            });  
        } else {  
        		addDate.each(function() {  
                $(this).prop("checked", false);  
            });  
        }  
    }); 
    
    //已绑定 全选
    $("#allPartOnGrid").click(function() {
	    	var removeDate = $(":checkbox[group=removeDate]");
	    	if ($(this).prop("checked")) {
	    		removeDate.each(function() {
	    			$(this).prop("checked", true);  
	    		});  
	    	} else {  
	    		removeDate.each(function() {  
	    			$(this).prop("checked", false);  
	    		});  
	    	}  
    }); 
    
    //获取全选数据
    function getSelectData(group){
    		var obj = $(":checkbox[group="+group+"]:checked");
    		var myArray = new Array();
    		var i =0;
    		obj.each(function() {
    			myArray[i++] = $(this).attr('dataId');
    		});
    		return myArray;
    }
    
    //绑定全部信息
    jQuery('.addBtn').on('click', function() {
	    	if(serverDataPartOnGrid.gridId == '0'){
			message('请选择需要绑定的网格信息!');
			return;
		}
	    	var dataInfo = getSelectData('addDate');
	    	if(dataInfo.length == 0){
	    		message('请选择需要绑定的部件信息!');
			return;
	    	}
	    	var d = {
	    			"gridId" : serverDataPartOnGrid.gridId ,
	    			"dataInfo" : dataInfo
	    		};
	    	var url = window.rootPath +'/ui/bindingGridArea/addDataAll';
	    	$("#right").mLoading("show");
        jQuery.ajax({
            url:encodeURI(url),
            cache:false,
            type :"post",
            data: JSON.stringify(d),
            dataType:"json",
            contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
            success:function(data){
            		$("#allPart").prop("checked", false); 
            		$("#allPartOnGrid").prop("checked", false); 
				message(data.msg);
            		serverTablePart.draw(false);
				serverTablePartOnGrid.draw(false);
				$("#right").mLoading("hide");
            }
        });
    });
    
    //绑定全部信息
    jQuery('.deleteBtn').on('click', function() {
    		var dataInfo = getSelectData('removeDate');
		if(dataInfo.length == 0){
			message('请选择需要移除的部件信息!');
			return;
		}
	    	var d = {
	    			"dataInfo" : dataInfo
	    		};
	    	var url = window.rootPath +'/ui/bindingGridArea/removeDataAll';
	    	$("#right").mLoading("show");
	    	jQuery.ajax({
	    		url:encodeURI(url),
	    		cache:false,
	    		type :"post",
	    		data: JSON.stringify(d),
	    		dataType:"json",
	    		contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
	    		success:function(data){
	    			$("#allPart").prop("checked", false); 
            		$("#allPartOnGrid").prop("checked", false); 
	    			message(data.msg);
	    			serverTablePart.draw(false);
	    			serverTablePartOnGrid.draw(false);
	    			$("#right").mLoading("hide");
	    		}
	    	});
    });
    	
    
    
    ////////////////初始化模型的树结构/////////////////////////
    var modalSetting = {
        edit:{
            enable: false,
            showRemoveBtn:false,
            showRenameBtn:false,
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
                rootParentId: 0
            }
        },
        view:{
            showLine:true
        },
        check: {
			enable: false,
			chkStyle: "radio",
			radioType: "level"
		},
        callback:{
            onClick:getDivsionGridAreaInfo
        }

    };
    
    //获取当前区域的网格信息
    function getDivsionGridAreaInfo(e, treeId, treeNode){
    		var Id=treeNode.id;
		//if('0' == Id) return;
    		serverDataGrid.divisionId = Id;
    		serverDataPartOnGrid.gridId = "0";
    		serverTableGrid.draw(false);
    		serverTablePartOnGrid.draw(false);
    }
    
    
    //初始化 层级树
    var primaryNode=[];
    var url = window.rootPath +'/ui/bindingGridArea/getAllNodes';
    jQuery.ajax({
        url:url,
        cache:false,
        type :"get",
        data:'',
        dataType:"json",
        contentType:'application/json;charset=utf-8',//解决返回数据中的中文乱码问题
        success:function(data){
            primaryNode.push(
                {
                    id: 0,
                    name: "部门层级",
                    open: "true"
                    // iconSkin:"diy03"
                }
            );
            for (var i = 0; i < data.nodes.length; i++) {
                primaryNode.push(data.nodes[i]);
            }
            $.fn.zTree.init($("#hierarchyTree"),modalSetting,primaryNode);
        }
    });
    
    //绑定数据
    function addData(data,name){
    		if(serverDataPartOnGrid.gridId == '0'){
    			message('请选择需要绑定的网格信息!');
    			return;
    		}
        $.springLemonDialog({
            title:'系统提示',//标题   默认为   系统提示
            content:'是否要绑定'+name+'？',//确认文本
            bootstrapModalOption:{keyboard: true},
            clickButton:function(sender,modal,index){//按钮事件处理
                //index:0 确认    1：取消
                //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                if(index==0){
                    var url=window.rootPath+'/ui/bindingGridArea/addData';
                    var d = {
                            "gridId":serverDataPartOnGrid.gridId,
                            "id":data.id
                        };
                    $("#right").mLoading("show");
                    jQuery.ajax({
                        url:encodeURI(url),
                        cache:false,
                        type :"post",
                        data: JSON.stringify(d),
                        dataType:"json",
                        contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
                        success:function(data){
                        		message(data.msg);
                        		serverTablePart.draw(false);
							serverTablePartOnGrid.draw(false);
							$("#right").mLoading("hide");
                        }
                    });
                }
                $(this).closeDialog(modal);
            }
        });
    }
    
    //解绑数据
    function removeData(data,name){
    		$.springLemonDialog({
    			title:'系统提示',//标题   默认为   系统提示
    			content:'是否解除绑定'+name+'？',//确认文本
    			bootstrapModalOption:{keyboard: true},
    			clickButton:function(sender,modal,index){//按钮事件处理
    				//index:0 确认    1：取消
    				//sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
    				if(index==0){
    					var url=window.rootPath+'/ui/bindingGridArea/removeData/'+data.id;
    					$("#right").mLoading("show");
    					jQuery.ajax({
    						url:encodeURI(url),
    						cache:false,
    						type :"post",
    						data: '',
    						dataType:"json",
    						contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
    						success:function(data){
    							message(data.msg);
    							serverTablePart.draw(false);
    							serverTablePartOnGrid.draw(false);
    							$("#right").mLoading("hide");
    						}
    					});
    				}
    				$(this).closeDialog(modal);
    			}
    		});
    }
    
})();